package com.andova.module;

import android.app.Activity;
import android.app.Application;

import com.andova.lifecycle.ILifecycle;
import com.andova.module.api.IModuleManager;
import com.andova.module.api.IModuleOptions;
import com.andova.module.api.IModuleProvider;
import com.andova.module.app.ModuleLifecycle;
import com.andova.module.dao.ModuleDaoManager;
import com.andova.module.dao.ModuleItem;
import com.andova.module.db.SQLiteHelper;

import java.util.List;
import java.util.Map;

import androidx.collection.ArrayMap;

/**
 * Created by Administrator on 2018-03-21.
 *
 * @author kzaxil
 * @since 1.0.0
 */
public class ModuleManager implements IModuleManager {
    private SQLiteHelper mSqlHelper;
    private IModuleOptions mOptions;
    private IModuleProvider mProvider;
    private ModuleDaoManager mDaoManager;

    private Map<Activity, Integer> mCheckedGridViewIdMap = new ArrayMap<>(1);
    private Map<Activity, Integer> mUncheckedGridViewIdMap = new ArrayMap<>(1);

    private boolean mIsInit = false;

    @Override
    public ModuleDaoManager getModuleDaoManager() {
        return mDaoManager;
    }

    @Override
    public IModuleOptions getModuleOptions() {
        return mOptions;
    }

    @Override
    public IModuleManager checkedGridViewId(Activity activity, int id) {
        if (!mIsInit) return this;
        mCheckedGridViewIdMap.put(activity, id);
        return this;
    }

    @Override
    public IModuleManager uncheckedGridViewId(Activity activity, int id) {
        if (!mIsInit) return this;
        mUncheckedGridViewIdMap.put(activity, id);
        return this;
    }

    @Override
    public int checkedGridViewId(Activity activity) {
        return mCheckedGridViewIdMap.get(activity) == null ? 0 : mCheckedGridViewIdMap.get(activity);
    }

    @Override
    public int uncheckedGridViewId(Activity activity) {
        return mUncheckedGridViewIdMap.get(activity) == null ? 0 : mUncheckedGridViewIdMap.get(activity);
    }

    @Override
    public ILifecycle initialize(Application application, IModuleOptions options, IModuleProvider provider) {
        mIsInit = true;
        mOptions = options;
        mProvider = provider;
        mDaoManager = new ModuleDaoManager(new SQLiteHelper(application, options.version()), provider);
        return new ModuleLifecycle();
    }

    /**
     * 获取已添加的模块集
     */
    @Override
    public List<ModuleItem> available() {
        return mDaoManager.getCheckedModules();
    }

    /**
     * 获取未添加的模块集
     */
    @Override
    public List<ModuleItem> unavailable() {
        return mDaoManager.getUncheckedModules();
    }

    @Override
    public void removeCheckedGridViewId(Activity activity) {
        mCheckedGridViewIdMap.remove(activity);
    }

    @Override
    public void removeUncheckedGridViewId(Activity activity) {
        mUncheckedGridViewIdMap.remove(activity);
    }
}
